import { defineStore } from 'pinia'

export const useCartStore = defineStore('cart', {
  state: () => ({
    items: [], // {skuId, title, price, qty, image}
  }),
  getters: {
    totalCount: (state) => state.items.reduce((sum, it) => sum + it.qty, 0),
    totalPrice: (state) => state.items.reduce((sum, it) => sum + it.qty * it.price, 0),
  },
  actions: {
    async reload() {
      const { listCart } = await import('@/services/cart')
      const res = await listCart()
      if (res?.code === 200 && Array.isArray(res?.data)) {
        this.items = res.data
      }
    },
    async addItemApi(payload) {
      const { addToCart } = await import('@/services/cart')
      const res = await addToCart(payload)
      await this.reload()
      return res
    },
    async updateQtyApi(payload) {
      const { updateCartQuantity } = await import('@/services/cart')
      console.log('stores/cart.js - updateQtyApi接收到的payload:', payload)
      
      const res = await updateCartQuantity(payload)
      
      // 只在更新成功的情况下才reload，避免覆盖前端已经计算好的数量
      if (res?.code === 200) {
        // 先尝试直接更新本地数据，而不是立即重新加载全部数据
        const itemIndex = this.items.findIndex(item => 
          item.id === payload.cartId || 
          item.productId === payload.cartId || 
          item.skuId === payload.cartId
        )
        
        if (itemIndex !== -1) {
          // 直接更新本地的商品数量
          this.items[itemIndex].quantity = payload.buyQuantity
          this.items[itemIndex].qty = payload.buyQuantity // 确保两种数量字段都更新
          console.log('stores/cart.js - 直接更新本地商品数量成功:', this.items[itemIndex])
        } else {
          // 如果找不到对应商品，才重新加载全部数据
          console.log('stores/cart.js - 未找到对应商品，重新加载全部数据')
          await this.reload()
        }
      } else {
        console.log('stores/cart.js - 更新失败，重新加载全部数据')
        await this.reload()
      }
      
      return res
    },
    async updateCheckedApi(payload) {
      const { updateCartChecked } = await import('@/services/cart')
      const res = await updateCartChecked(payload)
      await this.reload()
      return res
    },
    async removeItemsApi(ids) {
      console.log('stores/cart.js - 调用removeItemsApi，删除商品IDs:', ids)
      const { deleteCartItems } = await import('@/services/cart')
      const res = await deleteCartItems(ids)
      console.log('stores/cart.js - removeItemsApi调用成功，响应:', res)
      await this.reload()
      return res
    },
  },
})


